﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace CLFramework.Windows.Forms
{
    public partial class BubbleForm : Form
    {
        #region Properties

        protected int stayTime = 5000;
        public int StayTime
        {
            get { return stayTime; }
            set { stayTime = value; }
        }

        private int speed = 5;
        public PictureBox picBg;
        public Panel panelContainer;

        protected int Speed
        {
            get { return speed; }
            set { speed = value; }
        }

        private bool IsShown = false;

        public int OrgY { get; set; }

        #endregion

        #region Ctor.

        public BubbleForm()
        {
            InitializeComponent();
            this.TransparencyKey = this.BackColor;
            this.Opacity = 0;
            //this.panelContainer.Width = WidthMax - 17;
            //this.panelContainer.Height = HeightMax - 25;
        }

        public void AsyncDispose(string Content)
        {
            Action<string> funDelegate = new Action<string>(AddLabelControl);

            /*========================================================
             * 使用this.BeginInvoke方法
             * （也可以使用this.Invoke()方法）
            ========================================================*/

            // this.BeginInvoke(被调用的方法的委托，要传递的参数[Object数组])


            IAsyncResult aResult = funDelegate.BeginInvoke(Content, callbackm, this);
        }

        private void callbackm(IAsyncResult result)
        {
            if (result.IsCompleted)
            {
                //AlertContext.Dic_Acars_List.Add(((frmManualSendAcrarsAlert)result.AsyncState));
                AddDicList(result.AsyncState);
            }

        }

        public virtual void AddDicList(object obj)
        {


        }

        public BubbleForm(string Content)
        {
            InitializeComponent();
            //this.TransparencyKey = this.BackColor;
            this.Opacity = 0;

            //AddLabelControl(Content);
            AsyncDispose(Content);


        }

        private void AddLabelControl(string Content)
        {

            Label lb = new Label();
            lb.BackColor = Color.Transparent;
            lb.Text = Content;
            lb.Padding = new Padding(16, 36, 16, 16);
            lb.Dock = DockStyle.Fill;
            lb.AutoSize = false;
            lb.Font = new System.Drawing.Font("宋体", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            lb.MouseClick += new MouseEventHandler((sender, e) =>
            {
                if (e.X > 204 && e.X < 228 && e.Y > 0 && e.Y < 20)
                {
                    timerScrollUp.Enabled = false;
                    timerStay.Enabled = false;
                    timerScrollDown.Enabled = true;
                }
            });
            lb.MouseMove += new MouseEventHandler((s, e) =>
            {
                if (e.X > 204 && e.X < 228 && e.Y > 0 && e.Y < 20)
                {
                    this.Cursor = Cursors.Hand;
                }
                else
                {
                    this.Cursor = Cursors.Default;
                }
            });
            picBg.Controls.Add(lb);
        }

        public BubbleForm(UserControl uc)
        {
            InitializeComponent();
            this.TransparencyKey = this.BackColor;
            this.Opacity = 0;

            this.panelContainer.Width = WidthMax - 17;
            this.panelContainer.Height = HeightMax - 25;
            this.panelContainer.Controls.Add(uc);
        }

        #endregion

        #region Methods

        public void ScrollShow()
        {
            this.Width = WidthMax;
            this.Height = 0;
            this.timerScrollUp.Enabled = true;
        }

        protected void ScrollUp()
        {
            if (Height < HeightMax)
            {
                this.Height += Speed;
                this.Location = new Point(this.Location.X, this.Location.Y - Speed);

                if (this.Opacity != 1.00)
                {
                    double newop = this.Opacity + (Speed * 1.00 / (HeightMax - Height));
                    this.Opacity = newop > 1.00 ? 1.00 : newop;
                }
            }
            else
            {
                this.timerScrollUp.Enabled = false;
                this.timerStay.Enabled = true;
            }
        }

        protected void ScrollDown()
        {
            if (Height > Speed)
            {
                this.Height -= Speed;
                this.Location = new Point(this.Location.X, this.Location.Y + Speed);

                if (this.Opacity != 0.00)
                {
                    double newop = this.Opacity - (Speed * 1.00 / (this.Height - Speed));
                    this.Opacity = newop < 0.00 ? 0.00 : newop;
                }
            }
            else
            {
                this.timerScrollDown.Enabled = false;
                BubbleContainer.Hide(this);
                this.Close();
            }
        }

        #endregion

        #region EventHandlers

        protected void timerScrollUp_Tick(object sender, EventArgs e)
        {
            if (!IsShown)
            {
                if (BubbleContainer.CanShow())
                {
                    this.Show();
                    BubbleContainer.GetPoint(this);
                    this.timerStay.Interval = StayTime;
                    IsShown = true;
                }
            }
            else
            {
                ScrollUp();
            }
        }

        protected void timerStay_Tick(object sender, EventArgs e)
        {
            timerStay.Enabled = false;
            timerScrollDown.Enabled = true;
        }

        protected void timerScrollDown_Tick(object sender, EventArgs e)
        {
            ScrollDown();
        }

        #endregion

        #region Global Control

        static object locker = new object();

        public static int HeightMax = 163;

        public static int WidthMax = 226;

        public static int LineSpace = 15;

        #endregion

        #region Designer

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BubbleForm));
            this.timerScrollUp = new System.Windows.Forms.Timer(this.components);
            this.timerStay = new System.Windows.Forms.Timer(this.components);
            this.timerScrollDown = new System.Windows.Forms.Timer(this.components);
            this.picBg = new System.Windows.Forms.PictureBox();
            this.panelContainer = new System.Windows.Forms.Panel();
            ((System.ComponentModel.ISupportInitialize)(this.picBg)).BeginInit();
            this.SuspendLayout();
            // 
            // timerScrollUp
            // 
            this.timerScrollUp.Interval = 10;
            this.timerScrollUp.Tick += new System.EventHandler(this.timerScrollUp_Tick);
            // 
            // timerStay
            // 
            this.timerStay.Interval = 10;
            this.timerStay.Tick += new System.EventHandler(this.timerStay_Tick);
            // 
            // timerScrollDown
            // 
            this.timerScrollDown.Interval = 10;
            this.timerScrollDown.Tick += new System.EventHandler(this.timerScrollDown_Tick);
            // 
            // picBg
            // 
            this.picBg.Dock = System.Windows.Forms.DockStyle.Fill;
            this.picBg.Image = ((System.Drawing.Image)(resources.GetObject("picBg.Image")));
            this.picBg.Location = new System.Drawing.Point(0, 0);
            this.picBg.Name = "picBg";
            this.picBg.Size = new System.Drawing.Size(228, 155);
            this.picBg.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.picBg.TabIndex = 0;
            this.picBg.TabStop = false;
            // 
            // panelContainer
            // 
            this.panelContainer.BackColor = System.Drawing.Color.White;
            this.panelContainer.Location = new System.Drawing.Point(261, 150);
            this.panelContainer.Name = "panelContainer";
            this.panelContainer.Size = new System.Drawing.Size(31, 12);
            this.panelContainer.TabIndex = 1;
            // 
            // BubbleForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.White;
            this.ClientSize = new System.Drawing.Size(228, 155);
            this.Controls.Add(this.panelContainer);
            this.Controls.Add(this.picBg);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "BubbleForm";
            this.Opacity = 0D;
            this.ShowInTaskbar = false;
            this.TopMost = true;
            ((System.ComponentModel.ISupportInitialize)(this.picBg)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Timer timerScrollUp;
        private System.Windows.Forms.Timer timerStay;
        private System.Windows.Forms.Timer timerScrollDown;

        #endregion
    }

    public class BubbleContainer
    {
        public static int MaxShowingCount;

        static BubbleContainer()
        {

            Screen[] screens = Screen.AllScreens;
            Screen screen = screens[0];
            Point point = new Point(screen.WorkingArea.Width - BubbleForm.WidthMax, screen.WorkingArea.Height - 34);

            MaxShowingCount = (screen.WorkingArea.Height - 34) / (BubbleForm.HeightMax + BubbleForm.LineSpace);
            plist = new Point[MaxShowingCount];

            for (int i = 0; i < MaxShowingCount; i++)
            {
                plist[i] = new Point(screen.WorkingArea.Width - BubbleForm.WidthMax - 20, screen.WorkingArea.Height - 34 - (BubbleForm.HeightMax + BubbleForm.LineSpace) * i);
            }
        }

        static Point[] plist;
        static List<int> usedPoints = new List<int>();

        public static bool CanShow()
        {
            if (usedPoints.Count < MaxShowingCount)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static void GetPoint(BubbleForm bb)
        {
            Point np;

            for (int i = 0; i < plist.Count(); i++)
            {
                if (!usedPoints.Contains(plist[i].Y))
                {
                    np = plist[i];
                    bb.OrgY = np.Y;
                    usedPoints.Add(np.Y);
                    bb.Location = np;
                    return;
                }
            }
        }

        public static void Hide(BubbleForm bb)
        {
            usedPoints.Remove(bb.OrgY);
        }

        static object locker = new object();
    }
}
